<!--配送商端-销售管理-批发销售订单列表-批量确认-->
<template>
  <div class="batch-confirm">
    <el-container class="batch-confirm-container-box">
      <div
        class="batch-confirm-box"
        v-if="isBatchConfirm">
        <div class="header-box">
          <el-checkbox
            :indeterminate="isIndeterminate"
            v-model="isSelectedAll"
            @change="handleCheckAllChange"
          >全选</el-checkbox>
          <div class="total-amount-wrapper">
            总计  {{ orderTotalAmount | getFormatterPrice }}
          </div>
        </div>
        <el-collapse>
          <el-collapse-item
            v-for="(item,index) in orderDetailList"
            :key="index">
            <template slot="title">
              <el-checkbox-group
                v-model="selectedOrder"
                @change="handleCheckedChange">
                <el-checkbox :label="item">平台销售订单编号：{{ getOrderCode(item) }}</el-checkbox>
              </el-checkbox-group>
            </template>

            <div class="formToptext">
              <order-base-info
                :base-info="getOrderBaseInfo(item)"
              />
            </div>
            <order-product-table
              :product-data="item.items"
              :columns="columns"
            />
          </el-collapse-item>
        </el-collapse>
      </div>
      <div
        v-else
        v-loading="topLoading">
        <h3 class="title">订单编号 {{ signalOrderInfo.purchaseOrderCode }}</h3>
        <el-header height="auto">
          <div class="form-top-text">
            <order-base-info
              :base-info="signalOrderInfo"
            />
          </div>
        </el-header>
        <order-product-table
          :product-data="signalOrderList"
          :columns="columns"
        />
        <el-pagination
          class="pagination"
          @size-change="complatehandleSizeChange"
          @current-change="complatehandleCurrentChange"
          :current-page="curPage"
          :page-sizes="PAGE_NUMBER"
          :page-size="pageSize"
          :layout="PAGINATION_LAYOUT"
          :total="totalElements"
        />
      </div>
      <audit-dialog
        :dialog-visible.sync="auditDialogShow"
        :is-reject="isRejectAudit"
        :loading="auditLoading"
        @submitAudit="handleSubmitAudit"
        @closeDialog="auditDialogShow = false"
      />

    </el-container>
    <!-- 分页模块 -->
    <el-pagination
      class="pagination"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
      :current-page="curPage"
      :page-sizes="PAGE_NUMBER"
      :page-size="pageSize"
      :layout="PAGINATION_LAYOUT"
      :total="totalElements"
    />
  </div>
</template>

<script>
import ElEditable from '@components/el-editable/index.vue'
import OrderBaseInfo from '@/moduleComponents/beforeSettle/distributorSide/salesManagement/orderBaseInfo'
import OrderProductTable from '@/moduleComponents/beforeSettle/distributorSide/salesManagement/orderProductTable'
import AuditDialog from '@/moduleComponents/beforeSettle/distributorSide/salesManagement/auditDialog'

import { BATCH_TABLE_COLUMNS, ORDER_BASE_INFO } from './const.js'
import { isObject, cloneDeep, isString } from 'lodash'
import { PAGE_NUMBER, PAGINATION_LAYOUT } from '@const/common.js'
// import { deliverAddress } from '@const/storageCenterApi'
import {
  batchConfirmOrderList,
  batchConfirmOrder,
  deliverAddress
} from '@const/beforeSettleApi'
import { getFormatterPrice } from '@const/filter'

export default {
  name: 'BatchConfirm',
  components: { ElEditable, OrderBaseInfo, OrderProductTable, AuditDialog },

  data () {
    return {
      topLoading: false,
      isSelectedAll: false,
      isIndeterminate: false,
      // 批量确认信息
      orderDetailList: [],
      baseInfo: ORDER_BASE_INFO, // 列表上面基础信息
      signalOrderInfo: [],
      signalOrderList: [],
      addressInfo: {}, // 地址信息
      curPage: 1,
      PAGE_NUMBER,
      PAGINATION_LAYOUT,
      pageSize: PAGE_NUMBER[0],
      totalElements: 0,
      selectedOrder: [],
      auditDialogShow: false,
      isRejectAudit: false,
      auditLoading: false,
      columns: BATCH_TABLE_COLUMNS // table列表表头
      // 分页配置信息
    }
  },
  computed: {
    isBatchConfirm () {
      return (
        this.$route.query.isBatchConfirm === true ||
        this.$route.query.isBatchConfirm === 'true'
      )
    },
    id () {
      return this.$route.query.id
    },
    selectedIds () {
      return this.selectedOrder.map(item => item.order.id)
    },
    orderTotalAmount () {
      return this.selectedOrder.reduce(
        (pre, cur) => pre + cur.order.orderTotalAmount,
        0
      )
    }
  },
  filters: {
    getFormatterPrice
  },
  mounted () {
    this.getBatchConfirmOrderList()
    let obj = {}
    obj = {
      type: 'btn',
      arr: [
        {
          type: 'button',
          noReturn: true,
          val: '返回',
          handle: this.back
        },
        {
          type: 'danger',
          val: '拒绝订单',
          handle: this.handleAuditReject
        },
        {
          type: 'primary',
          val: '确认订单',
          handle: this.handleAuditPass
        }
      ]
    }
    this.$store.commit('changeLayoutHandle', obj)
  },
  methods: {
    handleSizeChange (size) {
      this.pageSize = size
      this.getWholesaleOrderList()
    },
    handleCurrentChange (curPage) {
      this.curPage = curPage
      this.getWholesaleOrderList()
    },
    handleCheckAllChange (isSelectedAll) {
      this.selectedOrder = isSelectedAll ? this.orderDetailList : []
      this.isIndeterminate = false
    },
    handleCheckedChange (checked) {
      let checkedCount = checked.length
      this.isSelectedAll = checkedCount === this.orderDetailList.length
      this.isIndeterminate =
        checkedCount > 0 && checkedCount < this.orderDetailList.length
    },
    handleSubmitAudit (auditFormValue) {
      // if (this.isRejectAudit && !auditFormValue.remark) return this.$message.warning('请填写拒绝原因')
      const selectedIdList = isString(this.selectedIds)
        ? [this.selectedIds]
        : this.selectedIds
      const idList = isString(this.id) ? [this.id] : this.id
      const params = {
        ids: this.isBatchConfirm ? selectedIdList : idList,
        state: !this.isRejectAudit
        // remark: auditFormValue.remark
      }
      this.auditLoading = true
      this.$axios
        .post(batchConfirmOrder, params)
        .then(({ data }) => {
          if (Number(data.code) === 0) {
            this.$message.success('操作成功')
            this.$router.push(
              '/distributorSide/salesManagement/wholesaleOrder'
            )
          }
        })
        .catch(e => {})
        .finally(() => {
          this.auditLoading = false
          this.auditDialogShow = false
        })
    },
    getOrderCode (item) {
      return item.order.purchaseOrderCode
    },
    getOrderBaseInfo (item) {
      // 获取订单基本信息
      const batchBaseInfo = Object.assign({}, item.order, this.addressInfo)
      const orderBaseData = this.isBatchConfirm ? batchBaseInfo : item
      const customForm = { ...this.baseInfo }
      return Object.keys(customForm).map(key => {
        return {
          label: this.baseInfo[key],
          value: orderBaseData[key]
        }
      })
    },
    getBatchConfirmOrderList () {
      // const params = isString(this.id) ? [this.id] : this.id
      const params = {
        page: this.curPage,
        pageSize: this.pageSize,
        ids: [this.id]
      }
      this.$axios.post(batchConfirmOrderList, params)
        .then(({ data }) => {
          if (Number(data.code) !== 0) return
          this.orderDetailList = data.payload || []
          const { order, items } = data.payload[0]
          let obj = data.payload[0].pageBean
          this.totalElements = obj.totalElements
          this.signalOrderList = obj.content
          const addressId = order.receiveAddressId
          this.getAddressData(order, addressId)
        })
    },
    getAddressData (baseInfo, id) {
      this.topLoading = true
      this.$axios
        .post(`${deliverAddress}?id=${id}`)
        .then(({ data }) => {
          if (Number(data.code) !== 0) return
          const {
            province,
            city,
            area,
            detailedAddress,
            userName,
            userPhone
          } = data.payload
          this.addressInfo = {
            receiveAddress: `${province} ${city} ${area} ${detailedAddress}`,
            linkMan: userName,
            linkPhone: userPhone
          }
          const topData = Object.assign({}, baseInfo, this.addressInfo)
          this.signalOrderInfo = this.getOrderBaseInfo(topData)
        })
        .catch(e => {})
        .finally(() => {
          this.topLoading = false
        })
    },
    back () {
      this.$router.go(-1)
    },
    complatehandleSizeChange (size) {
      this.pageSize = size
      this.getBatchConfirmOrderList()
    },
    complatehandleCurrentChange (curPage) {
      this.curPage = curPage
      this.getBatchConfirmOrderList()
    },
    handleAuditReject () {
      if (this.isBatchConfirm && this.selectedOrder.length === 0) {
        this.$message.error('请选择要确认的订单')
        return
      }
      this.isRejectAudit = true
      this.auditDialogShow = true
    },
    handleAuditPass () {
      if (this.isBatchConfirm && this.selectedOrder.length === 0) {
        this.$message.error('请选择要确认的订单')
        return
      }
      this.isRejectAudit = false
      this.auditDialogShow = true
    }
  }
}
</script>

<style lang="less">
.batch-confirm {
  position: relative;
  .batch-confirm-container-box {
    height: 100%;
    overflow: auto;
    .pagination {
      padding-top: 10px;
      display: flex;
      justify-content: flex-end;
      padding-right: 0;
    }
  }
  .pagination {
    position: absolute;
    right: 0;
  }
  .batch-confirm-box {
    .header-box {
      display: flex;
      flex-direction: row;
      justify-content: space-between;

      .total-amount-wrapper {
        font-size: 20px;
        font-weight: 500;
        margin-bottom: 10px;
      }
    }
  }
}
</style>
